//
//  MQTTManager.m
//  MQTT-Demo
//
//  Created by 赵国腾 on 2020/4/12.
//  Copyright © 2020 zhaoguoteng. All rights reserved.
//

#import "MQTTManager.h"
#import <MQTTClient/MQTTClient.h>

static NSString * const kMQTTTopic = @"testtopic/gaven/1001";

static MQTTManager *instance = nil;

@interface MQTTManager () <MQTTSessionDelegate>

@property(nonatomic, strong) MQTTSession *mqttSession;

@end

@implementation MQTTManager

+ (instancetype)share {
        
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[MQTTManager alloc] init];
    });
    
    return instance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        
    }
    return self;
}

- (MQTTSession *)mqttSession {
    if (!_mqttSession) {
        _mqttSession = [[MQTTSession alloc] init];
        
        MQTTCFSocketTransport *transport = [[MQTTCFSocketTransport alloc] init];
        transport.host = @"broker.emqx.io";
        transport.port = 1883;
        
        _mqttSession.transport = transport;
    }
    return _mqttSession;
}

- (void)connect {
    self.mqttSession.delegate = self;
    
    [self.mqttSession connectWithConnectHandler:^(NSError *error) {
        
        if (error) {
            NSLog(@"##MQTT 连接失败 %@", error.localizedDescription);
        } else {
            NSLog(@"##MQTT 连接成功");
                        
            [self.mqttSession subscribeToTopic:kMQTTTopic
                                       atLevel:MQTTQosLevelExactlyOnce
                              subscribeHandler:^(NSError *error, NSArray<NSNumber *> *gQoss) {
                if (error) {
                    NSLog(@"##MQTT 订阅 %@ %@", kMQTTTopic, error.localizedDescription);
                } else {
                    NSLog(@"##MQTT 订阅 %@ 成功", kMQTTTopic);
                    NSLog(@"##MQTT gQoss = %@", gQoss);
                }
            }];
            
        }
    }];
}

#pragma mark - MQTTSessionDelegate
- (void)newMessage:(MQTTSession *)session
              data:(NSData *)data
           onTopic:(NSString *)topic
               qos:(MQTTQosLevel)qos
          retained:(BOOL)retained
               mid:(unsigned int)mid {
    
    if ([topic isEqualToString:kMQTTTopic]) {
        ChatBodyModel *bodyModel = [ChatBodyModel yy_modelWithJSON:data];
        NSLog(@"##MQTT newMessage topic=%@ %@ retained=%d", topic, bodyModel.yy_modelDescription, retained);
        [NSNotificationCenter.defaultCenter postNotificationName:@"kNewMessage" object:bodyModel];
        if (self.newMessageBlock) {
            self.newMessageBlock(bodyModel);
        }
    }
}

- (void)sendMsg:(ChatBodyModel *)model {
    [self.mqttSession publishData:model.yy_modelToJSONData onTopic:kMQTTTopic retain:YES qos:MQTTQosLevelAtLeastOnce publishHandler:^(NSError *error) {
        
        NSLog(@"publishData error: %@", error.debugDescription);
    }];
//    [self.mqttSession publishJson:model.yy_modelToJSONObject onTopic:kMQTTTopic];
}

@end
